package com.example.administrator.myproject

import android.Manifest
import android.content.pm.PackageManager
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.view.View
import android.widget.TextView
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_ditu.*
import com.baidu.location.BDLocation
import com.baidu.location.BDLocationListener
import com.baidu.location.LocationClient
import com.baidu.location.LocationClientOption
import com.baidu.mapapi.SDKInitializer
import com.baidu.mapapi.map.*
import com.baidu.mapapi.model.LatLng

class ditu : AppCompatActivity() {
    var mLocationClient: LocationClient? = null
    var positionText: TextView? = null
    private var baiduMap: BaiduMap? = null
    private var isFristLocate = true
    var temp:Int = 0
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mLocationClient = LocationClient(applicationContext)
        val option = LocationClientOption()
        option.isOpenGps = true // 打开gps
        option.setCoorType("bd09ll") // 设置坐标类型
        option.setScanSpan(1000)

        //设置locationClientOption
        mLocationClient!!.locOption = option
        // 注册监听器
        mLocationClient!!.registerLocationListener(MyLocationListener())
        // 启动
        mLocationClient!!.start()
        //注册定位监听器接口
        mLocationClient!!.registerLocationListener(MyLocationListener())
        SDKInitializer.initialize(applicationContext)
        setContentView(R.layout.activity_ditu)
        positionText = findViewById<View>(R.id.position_text_view) as TextView
        baiduMap = bmapView.getMap()
        baiduMap!!.isMyLocationEnabled=true

        val permissionList: MutableList<String> = ArrayList()
        if (ContextCompat.checkSelfPermission(
                        this@ditu,
                        Manifest.permission.ACCESS_FINE_LOCATION
                ) != PackageManager.PERMISSION_GRANTED
        ) {
            permissionList.add(Manifest.permission.ACCESS_FINE_LOCATION)
        }
        if (ContextCompat.checkSelfPermission(
                        this@ditu,
                        Manifest.permission.READ_PHONE_STATE
                ) != PackageManager.PERMISSION_GRANTED
        ) {
            permissionList.add(Manifest.permission.READ_PHONE_STATE)
        }
        if (ContextCompat.checkSelfPermission(
                        this@ditu,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE
                ) != PackageManager.PERMISSION_GRANTED
        ) {
            permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE)
        }
        if (!permissionList.isEmpty()) {
            val permissions = permissionList.toTypedArray()
            ActivityCompat.requestPermissions(this@ditu, permissions, 1)
        } else {
            requestLocation()
        }
    }
    private fun requestLocation() {
        mLocationClient!!.start()//有权限则进行定位
    }

    override fun onPause() {
        super.onPause()
        bmapView.onPause()
    }

    override fun onResume() {
        super.onResume()
        bmapView.onResume()
    }

    override fun onDestroy() {
        super.onDestroy()
        bmapView.onDestroy()
        mLocationClient!!.stop()
        baiduMap!!.isMyLocationEnabled=false
    }

    //处理回调
    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        when (requestCode) {
            1 -> if (grantResults.size > 0) {
                for (result in grantResults) {
                    if (result != PackageManager.PERMISSION_GRANTED) {
                        Toast.makeText(
                                this, "必须同意所有权限才能使用本程序",
                                Toast.LENGTH_SHORT
                        ).show()
                        finish()
                        return
                    }
                }
                requestLocation()
            } else {
                Toast.makeText(this, "发生未知错误", Toast.LENGTH_SHORT).show()
                finish()
            }
            else -> {
            }
        }
    }
    inner class MyLocationListener : BDLocationListener {
        override fun onReceiveLocation(p0: BDLocation?) {
            if (p0 != null){
                if (p0.getLocType() == BDLocation.TypeGpsLocation
                        || p0.getLocType() == BDLocation.TypeNetWorkLocation
                ){
                    navigateTo(p0)
                    if(temp == 0)
                        navigateTo1(p0)
                    temp++
                }
            }
        }

        fun onConnectHotSpotMessage(s: String?, i: Int) {}
    }

    private fun navigateTo(location: BDLocation) {
        if (isFristLocate) {
            Toast.makeText(this, "nav to " + location.addrStr, Toast.LENGTH_SHORT).show()
            val ll = LatLng(location.latitude, location.longitude)//赋值经纬度
            var update = MapStatusUpdateFactory.newLatLng(ll)//获取该经纬度的MapStatusUpdate对象
            baiduMap!!.animateMapStatus(update)//赋值移动
            update = MapStatusUpdateFactory.zoomTo(20f)//控制缩放级别
            baiduMap!!.animateMapStatus(update)//移动
            isFristLocate = false//防止多次移动
        }
        val locationBuilder = MyLocationData.Builder()
        locationBuilder.latitude(location.latitude)
        locationBuilder.longitude(location.longitude)
        var locationData:MyLocationData = locationBuilder.build()
        baiduMap!!.setMyLocationData(locationData)


    }
    private fun navigateTo1(location: BDLocation) {
        val point = LatLng(location.latitude-0.0005, location.longitude-0.0007)
        //构建Marker图标
        val othersCurrentMarker = BitmapDescriptorFactory.fromResource(R.drawable.mao2)
        //构建MarkerOption，用于在地图上添加Marker
        val option: OverlayOptions = MarkerOptions()
                .position(point)
                .icon(othersCurrentMarker)
        //在地图上添加Marker，并显示
        baiduMap!!.addOverlay(option)
    }

}
